import socket
import logging
import threading
from utils.handle_client_connection import ClientConnectionHandler
from utils.logger import get_logger

logger = get_logger(__name__)

class SocketServer:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    
    def start(self) -> None:
        try:
            self.server_socket.bind((self.host, self.port))
            self.server_socket.listen(5)
            logging.info(f"服务器正在监听TCP {self.host}:{self.port}")
            
            while True:
                client_socket, client_address = self.server_socket.accept()
                logging.info(f"新客户端连接：{client_address}")
                handler = ClientConnectionHandler()
                client_thread = threading.Thread(
                    target=handler.handle_client_connection,
                    args=(client_socket, client_address)
                )
                client_thread.daemon = True
                client_thread.start()
                
        except KeyboardInterrupt:
            logging.info("服务器正在关闭...")
        except Exception as e:
            logging.error(f"服务器运行时出错：{e}")
        finally:
            self.server_socket.close()

def main() -> None:
    server = SocketServer("0.0.0.0", 5858)
    server.start()

if __name__ == "__main__":
    main()